package com.mypage.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.SharedPreferences;

import com.baidu.platform.comapi.map.K;
import com.cloudcc.cloudframe.model.MenuTabModel;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class ListDataSave {  
    private SharedPreferences preferences;  
    private SharedPreferences.Editor editor;  
  
    public ListDataSave(Context mContext, String preferenceName) {  
        preferences = mContext.getSharedPreferences(preferenceName, Context.MODE_PRIVATE);  
        editor = preferences.edit();  
    }  
  
    /** 
     * 保存List 
     * @param tag 
     * @param datalist 
     */  
    public <T> void setDataList(String tag, List<T> datalist) {  
        if (null == datalist || datalist.size() <= 0)  {
        	 String strJson = preferences.getString(tag, null);  
        	 if(null==strJson){
        		 return;
        	 }else{
        		 editor.putString(tag, "1"); 
        		 editor.commit();  
        		 return;  
        	 }
        }
        Gson gson = new Gson();  
        //转换成json数据，再保存  
        String strJson = gson.toJson(datalist);  
//        editor.clear();
        editor.putString(tag, strJson);  
        editor.commit();  
  
    }  
    
    /** 
     * 保存map
     * @param <V>
     * @param tag 
     * @param datalist 
     */  
    public <T, V> void setDataMap(String tag, Map<T,V> datamap) {  
        if (null == datamap || datamap.size() <= 0)  {
        	 String strJson = preferences.getString(tag, null);  
        	 if(null==strJson){
        		 return;
        	 }else{
        		 editor.putString(tag, "1"); 
        		 editor.commit();  
        		 return;  
        	 }
        }
        Gson gson = new Gson();  
        //转换成json数据，再保存  
        String strJson = gson.toJson(datamap);  
//        editor.clear();
        editor.putString(tag, strJson);  
        editor.commit();  
  
    }  
    
  
    /** 
     * 获取List 
     * @param tag 
     * @return 
     */  
    public  List<MenuTabModel> getDataList(String tag) {  
        List<MenuTabModel> datalist=new ArrayList<MenuTabModel>();  
        String strJson = preferences.getString(tag, null);  
        if (null == strJson) {  
            return datalist;  
        }  
        try {
        	 Gson gson = new Gson();  
             datalist = gson.fromJson(strJson, new TypeToken<List<MenuTabModel>>() {  
             }.getType()); 
		} catch (Exception e) {
			// TODO: handle exception
		}
        
        return datalist;  
  
    }  
    public void delete(){
    	editor.clear();  
        editor.commit();  
    }
}